package com.itheima.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao ;
    @Override
    //根据用户名查询数据库获取用户信息和关联的角色信息，同时需要查询角色关联的权限信息
    public User findByUsername(String username) {
//        User user = userDao.findByUsername(username);
//        if(user==null){
//            return  null;
//        }
//        Integer id = user.getId();
//        Set<Role> roles = roleDao.findByUserId(id);
//        for (Role role : roles) {
//            Integer id1 = role.getId();
//            Set<Permission> byRoleId = permissionDao.findByRoleId(id1);
//            role.setPermissions(byRoleId);
//        }
//        user.setRoles(roles);
//        return null;
//    }
        User user = userDao.findByUsername(username);
        if(user==null){
            return null;
        }
        Integer id = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(id);
        for (Role role : roles) {
            Integer id1 = role.getId();
            Set<Permission> byRoleId = permissionDao.findByRoleId(id1);
            //让角色关联权限
            role.setPermissions(byRoleId);
        }
        //让用户关联角色
        user.setRoles(roles);
        return user;
    }
}
